<!--
 *@开发者: 刘翔
 *@创建时间: 2025-05-23 16:34:13
 *@描述: 病例类型分布 - 分三个图表展示 + 病组类型变动趋势
!-->
<template>
  <div class="page-title-12_4">
    <!-- 病组类型变动趋势折线图 -->
    <div class="page-title-12_4__trend-container">
      <div class="page-title-12_4__chart" ref="trendChartRef"></div>
    </div>
    <div class="page-title-12_4__charts-wrapper">
      <!-- 病例数占比图表 -->
      <div class="page-title-12_4__chart-container">
        <div class="page-title-12_4__chart" ref="occupancyChartRef"></div>
      </div>

      <!-- 次均超支结余图表 -->
      <div class="page-title-12_4__chart-container">
        <div class="page-title-12_4__chart" ref="avgBalanceChartRef"></div>
      </div>

      <!-- 超支结余图表 -->
      <div class="page-title-12_4__chart-container">
        <div class="page-title-12_4__chart" ref="totalBalanceChartRef"></div>
      </div>
    </div>
    <div class="page-title-12_4-bottom">
      <span v-html="card1.text1"></span>
    </div>
  </div>
</template>

<script>
import formList from '../components/formList/formList';
import * as echarts from 'echarts';

export default {
  // 组件名称
  name: 'pageTile12_4',
  // 组件参数 接收来自父组件的数据
  props: {},
  // 局部注册的组件
  components: {
    formList,
  },
  // 组件状态值
  data() {
    return {
      card1: {},
      // 三个图表实例
      occupancyChart: null,
      avgBalanceChart: null,
      totalBalanceChart: null,
      trendChart: null, // 病组类型变动趋势图表实例
    };
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  // 组件方法
  methods: {
    //卡片内容
    cardData(desc) {
      this.card1 = {
        text1: desc,
      };
    },
    // 初始化数据
    init(data) {
      if (data.data && data.data['病例类型分布']) {
        this.initCharts(data.data['病例类型分布']);
      }
      if (data.data && data.data['病组类型变动趋势']) {
        this.initTrendChart(data.data['病组类型变动趋势']);
      }
      //内容
      this.cardData(data.desc);
    },

    // 初始化所有图表
    initCharts(data) {
      // 数据处理函数：排序并保留2位小数
      const processData = (data, key) => {
        // 创建包含原始索引的数组对象
        const indexedData = data.map((item, index) => ({
          value: Math.floor(item[key] * 100) / 100,
          category: item['病例类型'],
          index,
        }));

        // 按值降序排序
        // indexedData.sort((a, b) => b.value - a.value);

        // 返回排序后的分类和数据
        return {
          categories: indexedData.map(item => item.category),
          values: indexedData.map(item => item.value),
        };
      };

      // 处理各项数据
      const occupancyResult = processData(data, '病例数占比');
      const avgBalanceResult = processData(data, '次均超支结余(元)');
      const totalBalanceResult = processData(data, '超支结余(万元)');

      // 初始化病例数占比图表
      this.initOccupancyChart(occupancyResult.categories, occupancyResult.values);
      // 初始化次均超支结余图表
      this.initAvgBalanceChart(avgBalanceResult.categories, avgBalanceResult.values);
      // 初始化超支结余图表
      this.initTotalBalanceChart(totalBalanceResult.categories, totalBalanceResult.values);
    },

    // 初始化病例数占比图表
    initOccupancyChart(categories, data) {
      if (!this.occupancyChart) {
        this.occupancyChart = echarts.init(this.$refs.occupancyChartRef);
      }
      const option = this.getBaseChartOption(categories, '病例数占比', data, '{c}%');
      this.occupancyChart.setOption(option);
    },

    // 初始化次均超支结余图表
    initAvgBalanceChart(categories, data) {
      if (!this.avgBalanceChart) {
        this.avgBalanceChart = echarts.init(this.$refs.avgBalanceChartRef);
      }
      const option = this.getBaseChartOption(categories, '次均超支结余(元)', data, '{c}元');
      this.avgBalanceChart.setOption(option);
    },

    // 初始化超支结余图表
    initTotalBalanceChart(categories, data) {
      if (!this.totalBalanceChart) {
        this.totalBalanceChart = echarts.init(this.$refs.totalBalanceChartRef);
      }
      const option = this.getBaseChartOption(categories, '超支结余(万元)', data, '{c}万元');
      this.totalBalanceChart.setOption(option);
    },

    //折线图
    initTrendChart(data_list) {
      this.data_list = data_list;

      // 获取所有中文key（排除'月份'）
      const allKeys = new Set();
      data_list.forEach(item => {
        Object.keys(item).forEach(key => {
          if (key !== '月份') {
            allKeys.add(key);
          }
        });
      });
      const chineseKeys = Array.from(allKeys);

      // 处理数据，确保每个时间点都有所有的key
      const processedData = data_list.map(item => {
        const newItem = { ...item };
        chineseKeys.forEach(key => {
          if (!(key in newItem)) {
            newItem[key] = 0;
          }
        });
        return newItem;
      });

      let myChart = echarts.init(this.$refs.trendChartRef);
      let option;
      const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de'];
      option = {
        color: colors,
        title: {
          text: '病组类型变动趋势',
          textStyle: {
            fontSize: 18,
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
        },
        legend: {
          data: chineseKeys,
          textStyle: {
            fontSize: 18,
          },
        },
        grid: {
          top: '50%',
          bottom: '0%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: processedData.map(item => item['月份']),
          axisLabel: {
            fontSize: 18,
          },
        },
        yAxis: {
          type: 'value',
          name: '占比(%)',
          offset: 40,
          nameTextStyle: {
            fontSize: 18,
          },
          axisLabel: {
            formatter: '{value}%',
            fontSize: 18,
          },
        },
        series: chineseKeys.map((key, index) => ({
          name: key,
          type: 'line',
          stack: 'Total',
          areaStyle: {}, // 添加区域填充
          emphasis: {
            focus: 'series',
          },
          data: processedData.map(item => Math.floor((item[key] || 0) * 100) / 100),
          label: {
            show: true,
            distance: (index + 1) * 15, // 每个系列的distance递增15
            formatter: '{c}%',
            fontSize: 18,
            position: 'top',
          },
        })),
      };

      option && myChart.setOption(option);
    },

    // 获取基础图表配置
    getBaseChartOption(categories, seriesName, data, labelFormatter = '{c}') {
      return {
        title: {
          text: seriesName,
          textStyle: {
            fontSize: 18,
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        grid: {
          left: '5%',
          right: '15%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: [
          {
            type: 'value',
            axisLabel: {
              formatter: '{value}',
              fontSize: 18,
            },
          },
        ],
        yAxis: {
          type: 'category',
          data: categories,
          offset: 20,
          axisLabel: {
            fontSize: 18,
          },
        },
        series: [
          {
            name: seriesName,
            type: 'bar',
            barWidth: 40,
            data: data.map(value => ({
              value,
              itemStyle: {
                color: value > 0 ? '#5470c6' : '#ee6666',
              },
              label: {
                show: true,
                fontSize: 18,
                position: 'right',
                color: '#000',
                textBorderWidth: 1,
                formatter: labelFormatter,
              },
            })),
          },
        ],
      };
    },
  },
  created() {},
  mounted() {},
  beforeDestroy() {
    // 销毁所有图表实例
    [this.occupancyChart, this.avgBalanceChart, this.totalBalanceChart, this.trendChart].forEach(chart => {
      if (chart) {
        chart.dispose();
      }
    });
  },
};
</script>

<style lang="less" scoped>
.page-title-12_4 {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;

  &__trend-container {
    width: 100%;
    background-color: #fff;
    border-radius: 4px;
    padding: 16px;
    margin: 20px;
  }

  &__charts-wrapper {
    display: flex;
    padding: 20px;
  }

  &__chart-container {
    width: 100%;
    background-color: #fff;
    border-radius: 4px;
    padding: 16px;
  }

  &__chart-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-bottom: 16px;
    text-align: center;
  }

  &__chart {
    width: 100%;
    height: 300px;
  }

  .page-title-12_4-bottom {
    margin: 0 20px;
    padding: 2%;
    display: flex;
    align-items: center;
    font-size: 1.7rem;
    height: 10%;
    line-height: 40px;
    background: #fff2ca;
    border-radius: 16px;
    border: 1px solid #000;
    .color-tips {
      color: #ff1310;
    }
  }
}
</style>
